package com.japstudy.controller;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.japstudy.entity.Grade;
import com.japstudy.entity.Question;
import com.japstudy.entity.StarWord;
import com.japstudy.entity.User;
import com.japstudy.entity.Word;
import com.japstudy.entity.WordSex;
import com.japstudy.service.IGradeService;
import com.japstudy.service.IStarWordService;
import com.japstudy.service.IWordService;
import com.japstudy.service.IWordSexService;
import com.japstudy.util.PageUtil;
import com.japstudy.util.UUIDUtil;

@Controller
@RequestMapping(value="/Word")
public class WordController {

	@Autowired
	private IWordService wordServiceImpl;
	@Autowired
	private IWordSexService wordSexServiceImpl;
	@Autowired
	private IGradeService gradeServiceImpl;
	@Autowired
	private IStarWordService starWordServiceImpl;
	
	@RequestMapping("/wordAddUI")
	public String wordAddUI(HttpServletRequest request) {
		List<Grade> allGrade = gradeServiceImpl.selectAll();
		List<WordSex> allWordSex = wordSexServiceImpl.selectAll();
		request.getSession().setAttribute("allGradeAdmin", allGrade);
		request.getSession().setAttribute("allWordSexAdmin", allWordSex);
		return "admin/word_add";
	}
	
	@RequestMapping("/wordAdd")
	public void wordAdd(Word word, HttpServletRequest request, HttpServletResponse response) throws IOException {
		word.setWordId(UUIDUtil.getUUID());
		java.util.Date nowDate = new java.util.Date();
		Date wordLastUpdateTime = new Date(nowDate.getTime());
		word.setWordLastUpdateTime(wordLastUpdateTime);
		int result = wordServiceImpl.add(word);
		if(1 == result) {
			response.sendRedirect(request.getContextPath() + "/Word/wordAddUI");
		}
	}
	
	@RequestMapping("/selectAll")
	public String selectAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectAll();
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		response.sendRedirect(request.getContextPath() + "/Word/wordListUi");
		return null;
	}
	
	@RequestMapping("/userSelectAll")
	public String userSelectAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectAll();
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		List<StarWord> starWords = starWordServiceImpl.selectAllByLoginUser(loginUser.getUserId());
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		request.getSession().setAttribute("allStarWords", starWords);
		response.sendRedirect(request.getContextPath() + "/Word/userWordListUi");
		return null;
	}
	
	@RequestMapping("/userSelectAllWrongWord")
	public String userSelectAllWrongWord(String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectAllWrongWordByUserId(userId);
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		response.sendRedirect(request.getContextPath() + "/Word/userWrongWordListUi");
		return null;
	}
	
	@RequestMapping("/userSelectAllStarWord")
	public String userSelectAllStarWord(String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectAllStarWordByUserId(userId);
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		response.sendRedirect(request.getContextPath() + "/Word/userStarWordListUi");
		return null;
	}
	
	@RequestMapping("/wordListUi")
	public String wordListUi() {
		return "admin/word_list";
	}
	
	@RequestMapping("/userWordListUi")
	public String userWordListUi() {
		return "user/word_list";
	}
	
	@RequestMapping("/userStarWordListUi")
	public String userStarWordListUi() {
		return "user/star_word_list";
	}
	
	@RequestMapping("/userWrongWordListUi")
	public String userWrongWordListUi() {
		return "user/wrong_word_list";
	}
	
	@RequestMapping("/selectByNameLike")
	public String selectByNameLike(String wordName, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectByNameLike(wordName);
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		response.sendRedirect(request.getContextPath() + "/Word/wordListUi");
		return null;
	}
	
	@RequestMapping("/userSelectByNameLike")
	public String userSelectByNameLike(String wordName, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectByNameLike(wordName);
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		List<StarWord> starWords = starWordServiceImpl.selectAllByLoginUser(loginUser.getUserId());
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		request.getSession().setAttribute("allStarWords", starWords);
		response.sendRedirect(request.getContextPath() + "/Word/userWordListUi");
		return null;
	}
	
	@RequestMapping("/userSelectWrongByNameLike")
	public String userSelectWrongByNameLike(String wordName, String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectWrongByNameLike(wordName, userId);
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		response.sendRedirect(request.getContextPath() + "/Word/userWrongWordListUi");
		return null;
	}
	
	@RequestMapping("/userSelectStarByNameLike")
	public String userSelectStarByNameLike(String wordName, String userId, HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Word> words = wordServiceImpl.selectStarByNameLike(wordName, userId);
		for (Word word : words) {
			Grade grade = word.getGrade();
			word.setGrade(gradeServiceImpl.selectById(grade.getGradeId()));
			WordSex wordSex = word.getWordSex();
			word.setWordSex(wordSexServiceImpl.selectById(wordSex.getWordSexId()));
		}
		List<Word> pageData = PageUtil.getPageData(words, 1, 10);
		request.getSession().setAttribute("realWordsAdmin", words);
		request.getSession().setAttribute("wordsAdmin", pageData);
		response.sendRedirect(request.getContextPath() + "/Word/userStarWordListUi");
		return null;
	}
	
	@RequestMapping("/pageCountChange")
	public @ResponseBody List<Word> pageCountChange(HttpServletRequest request, HttpServletResponse response, String pageCount, String nowPageNumber) {
		List<Word> words = (List<Word>) request.getSession().getAttribute("realWordsAdmin");
		int intPageCount = Integer.parseInt(pageCount);
		int intNowPageNumber = Integer.parseInt(nowPageNumber);
		int maxPage = PageUtil.getMaxPage(words, intPageCount);
		if(intNowPageNumber > maxPage) {
			intNowPageNumber = maxPage;
		}
		List<Word> pageData = PageUtil.getPageData(words, intNowPageNumber, intPageCount);
		return pageData;
	}
	
	@RequestMapping("/toPage")
	public @ResponseBody List<Word> toPage(HttpServletRequest request, HttpServletResponse response, String pageCount, String toPageNumber) {
		List<Word> words = (List<Word>) request.getSession().getAttribute("realWordsAdmin");
		int intPageCount = Integer.parseInt(pageCount);
		int intToPageNumber = Integer.parseInt(toPageNumber);
		List<Word> pageData = PageUtil.getPageData(words, intToPageNumber, intPageCount);
		return pageData;
	}
	
	@RequestMapping("/wordUpdateUi")
	public ModelAndView wordUpdateUi(String wordId, HttpServletRequest request){
		Word updateWord = wordServiceImpl.selectById(wordId);
		List<Grade> allGrade = gradeServiceImpl.selectAll();
		List<WordSex> allWordSex = wordSexServiceImpl.selectAll();
		request.getSession().setAttribute("allGradeAdmin", allGrade);
		request.getSession().setAttribute("allWordSexAdmin", allWordSex);
		ModelAndView mav = new ModelAndView("admin/word_update", "updateWordAdmin", updateWord);
		return mav;
	}
	
	@RequestMapping("/wordUpdate")
	public String wordUpdate(Word word, HttpServletRequest request, HttpServletResponse response) throws IOException {
		java.util.Date nowDate = new java.util.Date();
		Date wordLastUpdateTime = new Date(nowDate.getTime());
		word.setWordLastUpdateTime(wordLastUpdateTime);
		int result = wordServiceImpl.update(word);
		if(1 == result) {
			response.sendRedirect(request.getContextPath() + "/Word/selectAll");
		} else {
			response.sendRedirect(request.getContextPath() + "/Word/wordUpdateUi?wordId=" + word.getWordId());
		}
		return null;
	}
	
	@RequestMapping("/delete")
	public String delete(Word word, HttpServletRequest request, HttpServletResponse response) throws IOException {
		wordServiceImpl.delete(word);
		response.sendRedirect(request.getContextPath() + "/Word/selectAll");
		return null;
	}
	
	@RequestMapping("/testPaperChooseUi")
	public String testPaperChooseUi(HttpServletRequest request) {
		List<Grade> haveWordGrade = gradeServiceImpl.haveWordGrade();
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		String userId = loginUser.getUserId();
		List<Word> allWord = wordServiceImpl.selectAll();
		List<Word> starWord = wordServiceImpl.selectAllStarWordByUserId(userId);
		List<Word> wrongWord = wordServiceImpl.selectAllWrongWordByUserId(userId);
		if(starWord == null || starWord.size() <= 0) {
			request.getSession().setAttribute("noStar", 1);
		}
		if(wrongWord == null || wrongWord.size() <= 0) {
			request.getSession().setAttribute("noWrong", 1);
		}
		int maxQuestionCount = allWord.size();
		request.getSession().setAttribute("maxQuestionCount", maxQuestionCount);
		request.getSession().setAttribute("haveWordGrade", haveWordGrade);
		return "user/test_paper_choose";
	}
	
	@RequestMapping("/howMuchWordOfGrade")
	public @ResponseBody String howMuchWordOfGrade(@RequestBody List<Grade> grades) {
		List<Word> selectWordByGradeId = wordServiceImpl.selectByGradeId(grades);
		int maxQuestionCount = selectWordByGradeId.size();
		return String.valueOf(maxQuestionCount);
	}
	
	@RequestMapping("/howMuchWordOfGradeAndStar")
	public @ResponseBody String howMuchWordOfGradeAndStar(@RequestBody List<Grade> grades, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		String userId = loginUser.getUserId();
		List<Word> selectWordByGradeIdAndStar = wordServiceImpl.selectByGradeIdAndStar(grades, userId);
		int maxQuestionCount = selectWordByGradeIdAndStar.size();
		return String.valueOf(maxQuestionCount);
	}
	
	@RequestMapping("/howMuchWordOfGradeAndWrong")
	public @ResponseBody String howMuchWordOfGradeAndWrong(@RequestBody List<Grade> grades, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		String userId = loginUser.getUserId();
		List<Word> selectWordByGradeIdAndWrong = wordServiceImpl.selectByGradeIdAndWrong(grades, userId);
		int maxQuestionCount = selectWordByGradeIdAndWrong.size();
		return String.valueOf(maxQuestionCount);
	}
	
	@RequestMapping("/createTestPaper")
	public String createTestPaper(HttpServletResponse response, HttpServletRequest request,
			@RequestParam("gradeId") String[] gradeIds, String questionCount,
			String questionScope, String questionSex) throws IOException {
		List<Question> questions = new ArrayList<Question>();
		List<Grade> grades = new ArrayList<Grade>();
		for (String gradeId : gradeIds) {
			Grade grade = new Grade(gradeId, "");
			grades.add(grade);
		}
		List<Word> words = new ArrayList<Word>();
		if (questionScope.equals("all")) {
			words = wordServiceImpl.selectByGradeId(grades);
		} else if(questionScope.equals("star")) {
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			words = wordServiceImpl.selectByGradeIdAndStar(grades, loginUser.getUserId());
		} else if (questionScope.equals("wrong")) {
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			words = wordServiceImpl.selectByGradeIdAndWrong(grades, loginUser.getUserId());
		}
		int questionCountNum = Integer.parseInt(questionCount);
		int[] index = new int[questionCountNum];
		Random rand = new Random();
		label:
		for (int i = 0; i < index.length; i++) {
			int randIndex = rand.nextInt(words.size());
			for (int j = 0; j < i; j++) {
				if(index[j] == randIndex) {
					i--;
					continue label;
				}
			}
			index[i] = randIndex;
		}
		for (int i = 0; i < index.length; i++) {
			Question question = new Question(UUIDUtil.getUUID(), questionSex, words.get(index[i]), "", 0);
			questions.add(question);
		}
		request.getSession().setAttribute("realTestPaperQuestions", questions);
		request.getSession().setAttribute("nowPageQuestion", questions.get(0));
		request.getSession().setAttribute("testSex", questionSex);
		request.getSession().setAttribute("nowQuestionIndex", 1);
		request.getSession().setAttribute("maxQuestionIndex", index.length);
		if(questionSex.equals("chineseToJapanese")) {
			response.sendRedirect(request.getContextPath() + "/Word/userTestPaperChineseUi");
		} else {
			response.sendRedirect(request.getContextPath() + "/Word/userTestPaperJapaneseUi");
		}
		return null;
	}
	
	@RequestMapping("/userTestPaperChineseUi")
	public String userTestPaperChineseUi() {
		return "user/test_paper_chinese";
	}
	
	@RequestMapping("/userTestPaperJapaneseUi")
	public String userTestPaperJapaneseUi() {
		return "user/test_paper_japanese";
	}
}
